package com.fcscs.cservice.client.main.restaurants;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.form.AdapterField;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Time;
import com.extjs.gxt.ui.client.widget.form.TimeField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.fcscs.core.common.MainPaginationSearchModel;
import com.fcscs.core.common.SearchResultsContainer;
import com.fcscs.core.gwt.common.AsyncCallbackListener;
import com.fcscs.core.gwt.common.CoreConstants;
import com.fcscs.core.gwt.common.CoreConstants.ValidationListener;
import com.fcscs.core.gwt.common.CoreEnums.SubmitType;
import com.fcscs.core.gwt.common.FormSubmitListener;
import com.fcscs.core.gwt.common.SearchExecutor;
import com.fcscs.core.gwt.common.ui.BaseFormDialog;
import com.fcscs.core.gwt.common.ui.FcsFields.EasyClearCombobox;
import com.fcscs.core.gwt.common.ui.FcsFields.FormButton;
import com.fcscs.core.gwt.common.ui.FcsFormPanel;
import com.fcscs.core.gwt.common.ui.FcsPanel;
import com.fcscs.core.gwt.common.ui.IEFriendlyDateField;
import com.fcscs.cservice.client.common.CServiceConstants;
import com.fcscs.cservice.client.common.controller.BookingServiceController;
import com.fcscs.cservice.client.common.controller.CServiceCommonServiceController;
import com.fcscs.cservice.client.common.model.restaurants.BookingStatusGWTEnum;
import com.fcscs.cservice.client.common.model.restaurants.BookingStatusModelData;
import com.fcscs.cservice.client.common.model.restaurants.BookingViewModelData;
import com.fcscs.cservice.client.common.model.restaurants.GuestProfileTypeEnumModelData;
import com.fcscs.cservice.client.common.model.restaurants.GuestProfileTypeGWTEnum;
import com.fcscs.cservice.client.common.model.restaurants.SmokingOrNotGWTEnum;
import com.fcscs.cservice.client.common.model.restaurants.SmokingOrNotGWTEnumModelData;
import com.fcscs.cservice.client.common.model.restaurants.TitleModelData;
import com.fcscs.cservice.client.main.inroomdining.InRoomDiningHistoryGrid;
import com.fcscs.cservice.common.CServiceCommonEnums.BookingStatus;
import com.fcscs.cservice.common.CServiceCommonEnums.GuestProfileType;
import com.fcscs.cservice.common.CServiceCommonEnums.NotifyType;
import com.fcscs.cservice.domain.Title;
import com.fcscs.cservice.domain.model.BookingUpdate;
import com.fcscs.cservice.domain.model.BookingView;
import com.fcscs.share.gwt.common.ShareGWTConstants;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ResBookingDetailDialog extends BaseFormDialog<BookingUpdate> implements FormSubmitListener<BookingUpdate>{
	private MyFormPanel myFormPanel;
	private GuestBookingHistoryGrid bookHisGrid;
	private static ResBookingDetailDialog INSTANCE;
	private LayoutContainer lc1;
	private LayoutContainer lc2;
	private Label guestProfileNumLabel;
	private AdapterField guestProfileNumAF;

	private Label arriveDateLabel;
	private AdapterField arriveDateField;
	private Label departureDateLabel;
	private AdapterField departureDateField;
	private TextField<String> phoneField;
	private Label guestTypeLabel;
	private Label guestNameLabel;
	private AdapterField guestNameAF;
	private TextField<String> numOfPeopleField;
//	private TextField<String> roomNumAF;
	private Label roomNumLab;
	private AdapterField roomNumAF;
	private TextField<String> noteField;

	private BookingViewModelData bViewModel;
	private List<BookingViewModelData> bHistoryList;
	private FieldSet emailPhoneFieldSet;
	private FormButton saveBtn;
	private FormButton cancelBtn;
	private BookingView currModel;
	private EasyClearCombobox<GuestProfileTypeEnumModelData> guestTypeCombo;
	private ListStore<GuestProfileTypeEnumModelData> guestTypeStore;
	private CheckBox emailCheckBox;
	private CheckBox phoneCheckBox;
	private TextField<String> emailCheckField;
	private TextField<String> phoneCheckField;
	private EasyClearCombobox<TitleModelData> titleCombobox;
	private ListStore<TitleModelData> titleStore;
	private IEFriendlyDateField datetimeReser;
	private TimeField timeField;
	private Label dateTimeLabel;
	private HorizontalPanel lc2Hp1;
	private HorizontalPanel lc2Hp2;
	private HorizontalPanel lc2Hp3;
	private LayoutContainer container1;
	private LayoutContainer container2;
	private LayoutContainer container3;
	private Label noteLabel;
	private DateTimeFormat formatDate = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");
	private DateTimeFormat timeFormat = DateTimeFormat.getFormat("HH:mm");
	private FormSubmitListener<BookingUpdate> listener;
	private EasyClearCombobox<SmokingOrNotGWTEnumModelData> smokingCombox;
	private ListStore<SmokingOrNotGWTEnumModelData> smokingStore;
	private InRoomDiningHistoryGrid inDiningGrid;
	
	private EasyClearCombobox<BookingStatusModelData> bookingStatusCombox;
	private ListStore<BookingStatusModelData> bookingStatusStore;

	public static ResBookingDetailDialog getInstance(FormSubmitListener<BookingUpdate> fListener ,BookingViewModelData bViewModel) {
		if (null == INSTANCE) {
			INSTANCE = new ResBookingDetailDialog();
		}
		INSTANCE.listener = fListener;
		INSTANCE.clear();
		INSTANCE.updateBookingView(bViewModel.getEntity());
		INSTANCE.setHeading(CServiceConstants.CSERVICE_CONSTANTS.bookingDetail());
		INSTANCE.bViewModel = bViewModel;
		INSTANCE.loadTitleList(bViewModel.getEntity().getPropertyId());
		INSTANCE.newSearch();
		return INSTANCE;
	}

	private ResBookingDetailDialog() {
		myFormPanel = new MyFormPanel(this);
		add(myFormPanel);
		setSize(774, 780);
	}

	public class MyFormPanel extends FcsFormPanel<BookingUpdate> {

		protected MyFormPanel(FormSubmitListener<BookingUpdate> l) {
			super(l);
			setHeaderVisible(false);

			lc1 = new LayoutContainer();
			lc1.setLayout(new ColumnLayout());
			lc1.setBorders(false);

			LayoutContainer left1 = new LayoutContainer();
			FormLayout layout = new FormLayout();
			layout.setLabelAlign(LabelAlign.LEFT);
			layout.setLabelWidth(150);
			left1.setLayout(layout);

			guestProfileNumLabel = new Label();
			guestProfileNumLabel.setId("ResBookingDetailDialog_remarksLabel");

			guestProfileNumAF = new AdapterField(guestProfileNumLabel);
			guestProfileNumAF.setId("ResBookingDetailDialog_guestProfileNumAF");
			guestProfileNumAF.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.guestProfileNo());
			left1.add(guestProfileNumAF);

			arriveDateLabel = new Label();
			arriveDateLabel.setId("ResBookingDetailDialog_arriveDateField");
			arriveDateField = new AdapterField(arriveDateLabel);
			arriveDateField.setId("ResBookingDetailDialog_arriveField");
			arriveDateField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.arrivalDate());
			left1.add(arriveDateField);
			
			smokingCombox = new EasyClearCombobox<SmokingOrNotGWTEnumModelData>();
			smokingCombox.focus();
			smokingCombox.setId("ResBookingDetailDialog_smokingCombox");
			smokingCombox.setDisplayField(CoreConstants.FULLTNAME);
			smokingCombox.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.smokingorNonsmoking());
			smokingStore = new ListStore<SmokingOrNotGWTEnumModelData>();
			for(SmokingOrNotGWTEnum sone : SmokingOrNotGWTEnum.values()){
				smokingStore.add(new SmokingOrNotGWTEnumModelData(sone));
			}
			smokingCombox.setStore(smokingStore);
			smokingCombox.setTriggerAction(TriggerAction.ALL);
			left1.add(smokingCombox);
			
			
			titleCombobox = new EasyClearCombobox<TitleModelData>();
			titleCombobox.setId("ResBookingDetailDialog_titleCombobox");
			titleCombobox.setFieldLabel(ShareGWTConstants.SHARE_GWT_CONSTANTS.title());
			titleStore = new ListStore<TitleModelData>();
			titleCombobox.setStore(titleStore);
			titleCombobox.setDisplayField(CServiceConstants.TITLE);
			titleCombobox.setTriggerAction(TriggerAction.ALL);
			left1.add(titleCombobox);
			
			phoneField = new TextField<String>();
			phoneField.setId("ResBookingDetailDialog_phoneField");
			phoneField.setFieldLabel(CoreConstants.CORE_CONSTANTS.phone());
			left1.add(phoneField);
			phoneField.setValidator(new Validator() {
				@Override
				public String validate(Field<?> field, String value) {
					if (null != value && (!value.trim().isEmpty())
							&& (value.trim().length() < 1 || value.trim().length() > 50)) {
						return ShareGWTConstants.SHARE_GWT_MESSAGES.nameValid(
								CoreConstants.CORE_CONSTANTS.phone(), 0, 50);
					}
					return null;
				}
			});

			LayoutContainer right1 = new LayoutContainer();
			layout = new FormLayout();
			layout.setLabelAlign(LabelAlign.LEFT);
			layout.setLabelWidth(120);
			right1.setLayout(layout);

			guestNameLabel = new Label();
			guestNameLabel.setId("ResBookingDetailDialog_guestNameLabel");

			guestNameAF = new AdapterField(guestNameLabel);
			guestNameAF.setId("ResBookingDetailDialog_guestNameAF");
			guestNameAF.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.guestName());
			right1.add(guestNameAF);

			departureDateLabel = new Label();
			departureDateLabel.setId("ResBookingDetailDialog_departureDateLabel");
			departureDateField = new AdapterField(departureDateLabel);
			departureDateField.setId("ResBookingDetailDialog_departureDateField");
			departureDateField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.departureDate());
			right1.add(departureDateField);
			
			bookingStatusCombox = new EasyClearCombobox<BookingStatusModelData>();
			bookingStatusCombox.setId("ResBookingDetailDialog_smokingCombox");
			bookingStatusCombox.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.bookingStatus());
			bookingStatusStore = new ListStore<BookingStatusModelData>();
			for (BookingStatusGWTEnum be : BookingStatusGWTEnum.values()) {
				bookingStatusStore.add(new BookingStatusModelData(be));
			}
			
			bookingStatusCombox.setStore(bookingStatusStore);
			bookingStatusCombox.setDisplayField(CoreConstants.FULLTNAME);
			bookingStatusCombox.setTriggerAction(TriggerAction.ALL);
			right1.add(bookingStatusCombox);
			
			numOfPeopleField = new TextField<String>();
			numOfPeopleField.setId("ResBookingDetailDialog_numOfPeopleAF");
			numOfPeopleField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.numberOfPeople());
			right1.add(numOfPeopleField);
			numOfPeopleField.addListener(Events.Change, new Listener<FieldEvent>() {

				@Override
				public void handleEvent(final FieldEvent be) {
					String peopleNo = numOfPeopleField.getValue();
					if (null != peopleNo) {
						if (peopleNo.matches("^[0-9]+$")) {
							if (Integer.parseInt(peopleNo) <0 || Integer.parseInt(peopleNo) >10) {
								numOfPeopleField.forceInvalid( CoreConstants.CORE_MESSAGES.numericValueOutOfRange("0", "10"));
							}else {
								numOfPeopleField.clearInvalid();
							}
						}else{
							numOfPeopleField.forceInvalid( CServiceConstants.CSERVICE_CONSTANTS.pleaseEnterDigit());
						}
					}
				}
			});

			roomNumLab = new Label();
			roomNumLab.setId("ResBookingDetailDialog_roomNumLab");
			
			roomNumAF = new AdapterField(roomNumLab);
//			roomNumAF = new TextField<String>();
//			roomNumAF.setEnabled(false);
			roomNumAF.setId("ResBookingDetailDialog_roomNumAF");
			roomNumAF.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.roomNum());
			right1.add(roomNumAF);
//			roomNumAF.setValidator(new Validator() {
//				@Override
//				public String validate(Field<?> field, String value) {
//					if (null != value && (!value.trim().isEmpty())
//							&& (value.trim().length() < 0 || value.trim().length() > 20)) {
//						return ShareGWTConstants.SHARE_GWT_MESSAGES.nameValid(
//								CServiceConstants.CSERVICE_CONSTANTS.roomNum(), 0, 20);
//					}
//					return null;
//				}
//			});
			

			lc1.add(left1, new ColumnData(.55));
			lc1.add(right1, new ColumnData(.45));

			lc2 = new LayoutContainer();
			lc2.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "10px");
			lc2.setLayout(new ColumnLayout());
			lc2.setBorders(false);

			lc2Hp1 = new HorizontalPanel();
			lc2Hp1.setId("ResBookingDetailDialog_lc2Hp1");
			lc2.add(lc2Hp1);
			
			container1 = new LayoutContainer();
			container1.setLayout(new ColumnLayout());
			lc2Hp1.add(container1);
			
			guestTypeLabel = new Label(CoreConstants.CORE_MESSAGES.label(CServiceConstants.CSERVICE_CONSTANTS.guestType()));
			guestTypeLabel.setId("ResBookingDetailDialog_guestTypeLabel");
			container1.add(guestTypeLabel,new ColumnData(200));
			
			guestTypeCombo = new EasyClearCombobox<GuestProfileTypeEnumModelData>();
			guestTypeCombo.setWidth(200);
			guestTypeStore = new ListStore<GuestProfileTypeEnumModelData>();
			for(GuestProfileTypeGWTEnum fsi : GuestProfileTypeGWTEnum.values()){
				guestTypeStore.add(new GuestProfileTypeEnumModelData(fsi));
			}
			guestTypeCombo.setId("ResBookingDetailDialog_guestTypeCombo");
			guestTypeCombo.setDisplayField(CoreConstants.FULLTNAME);
			guestTypeCombo.setTriggerAction(TriggerAction.ALL);
			guestTypeCombo.setStore(guestTypeStore);
			container1.add(guestTypeCombo,new ColumnData(200));

			lc2Hp2 = new HorizontalPanel();
			lc2Hp2.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "5px");
			lc2Hp2.setId("ResBookingDetailDialog_lc2Hp1");
			lc2.add(lc2Hp2);
			
			container2 = new LayoutContainer();
			container2.setLayout(new ColumnLayout());
			lc2Hp2.add(container2);
			
			dateTimeLabel = new Label(CoreConstants.CORE_MESSAGES.label(CServiceConstants.CSERVICE_CONSTANTS.dateTimeReservation()));
			dateTimeLabel.setId("ResBookingDetailDialog_guestTypeLabel");
			container2.add(dateTimeLabel,new ColumnData(200));
			
			datetimeReser = new IEFriendlyDateField();
			datetimeReser.setId("ResBookingDetailDialog_datetimeReser");
			container2.add(datetimeReser,new ColumnData(200));
			
			timeField = new TimeField();
			timeField.setStyleAttribute(CServiceConstants.CSS_MARGINLEFT, "5px");
			timeField.setId("ResBookingDetailDialog_timeField");
			container2.add(timeField,new ColumnData(150));
			
			lc2Hp3 = new HorizontalPanel();
			lc2Hp3.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "5px");
			lc2Hp3.setId("ResBookingDetailDialog_lc2Hp1");
			lc2.add(lc2Hp3);
			
			container3 = new LayoutContainer();
			container3.setLayout(new ColumnLayout());
			lc2Hp3.add(container3);
			
			noteLabel = new Label(CServiceConstants.CSERVICE_CONSTANTS.note());
			noteLabel.setId("ResBookingDetailDialog_noteLabel");
			container3.add(noteLabel,new ColumnData(200));
			
			noteField = new TextField<String>();
			noteField.setId("ResBookingDetailDialog_noteAF");
			noteField.setValidator(new Validator() {
				@Override
				public String validate(Field<?> field, String value) {
					if (null != value && (!value.trim().isEmpty())
							&& (value.trim().length() < 0 || value.trim().length() > 500)) {
						return ShareGWTConstants.SHARE_GWT_MESSAGES.nameValid(
								CServiceConstants.CSERVICE_CONSTANTS.note(), 0, 500);
					}
					return null;
				}
			});
			container3.add(noteField,new ColumnData(200));

			
			emailPhoneFieldSet = new FieldSet();
			emailPhoneFieldSet.setHeading(CServiceConstants.CSERVICE_CONSTANTS.confirmationNoticeDes());
			
			LayoutContainer lc3Container = new LayoutContainer();
			lc3Container.setId("ResBookingDetailDialog_lc3Container");
			lc3Container.setLayout(new ColumnLayout());
			
			HorizontalPanel hp1 = new HorizontalPanel();
			hp1.setId("ResBookingDetailDialog_hp1");
			
			emailCheckBox = new CheckBox();
			emailCheckBox.setId("CreateMessageDialog_emailCheckBox_id");
			emailCheckBox.setBoxLabel(CoreConstants.CORE_CONSTANTS.email());
			lc3Container.add(emailCheckBox,new ColumnData(80));
			emailCheckBox.addListener(Events.OnClick, new Listener<BaseEvent>() {

				@Override
				public void handleEvent(BaseEvent be) {
					if (emailCheckBox.getValue()) {
						emailCheckField.setEnabled(true);
					}else {
						emailCheckField.setEnabled(false);
						emailCheckField.clear();
					}
				}
			});
			
			emailCheckField = new TextField<String>();
			emailCheckField.setId("ResBookingDetailDialog_emailField");
			lc3Container.add(emailCheckField, new ColumnData(350));
			emailCheckField.setEnabled(false);
			hp1.add(lc3Container);
			final String emailReg = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
			emailCheckField.setValidator(new Validator() {
				@Override
				public String validate(Field<?> field, String value) {
					if (!value.toUpperCase().matches(emailReg)) {
						return ShareGWTConstants.SHARE_GWT_CONSTANTS.emailErro();
					} else if (value.length() > 50) {
						return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(CoreConstants.CORE_CONSTANTS.email(),
								50);
					}
					return null;
				}
			});
			
			emailCheckField.addListener(Events.OnBlur, new Listener<BaseEvent>() {

				@Override
				public void handleEvent(BaseEvent be) {
					if (emailCheckBox.getValue() && null == emailCheckField.getValue()) {
						emailCheckField.forceInvalid(CoreConstants.CORE_CONSTANTS.requiredField());
					}
				}
			});
			

			LayoutContainer lc4Container = new LayoutContainer();
			lc4Container.setId("ResBookingDetailDialog_lc4Container");
			lc4Container.setLayout(new ColumnLayout());
			
			HorizontalPanel hp2 = new HorizontalPanel();
			hp2.setId("ResBookingDetailDialog_hp2");
			hp2.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "5px");
			
			phoneCheckBox = new CheckBox();
			phoneCheckBox.setId("CreateMessageDialog_phoneCheckBox_id");
			phoneCheckBox.setBoxLabel(CoreConstants.CORE_CONSTANTS.phone());
			lc4Container.add(phoneCheckBox,new ColumnData(80));
			phoneCheckBox.addListener(Events.OnClick, new Listener<BaseEvent>() {

				@Override
				public void handleEvent(BaseEvent be) {
					if (phoneCheckBox.getValue()) {
					 	phoneCheckField.setEnabled(true);
					}else {
						phoneCheckField.setEnabled(false);
						phoneCheckField.clear();
					}
				}
			});
			
			phoneCheckField = new TextField<String>();
			phoneCheckField.setId("ResBookingDetailDialog_phoneField");
			phoneCheckField.setEnabled(false);
			lc4Container.add(phoneCheckField,new ColumnData(350));
			phoneCheckField.setValidator(new Validator() {
				@Override
				public String validate(Field<?> field, String value) {
					if (phoneCheckBox.getValue() && (value.trim().isEmpty() || value.trim().length() > 50)) {
						return ShareGWTConstants.SHARE_GWT_MESSAGES.nameValid(
								CoreConstants.CORE_CONSTANTS.phone(), 0, 50);
					}
					return null;
				}
			});
			phoneCheckField.addListener(Events.OnBlur, new Listener<BaseEvent>() {

				@Override
				public void handleEvent(BaseEvent be) {
					if (phoneCheckBox.getValue() && null == phoneCheckField.getValue()) {
						phoneCheckField.forceInvalid(CoreConstants.CORE_CONSTANTS.requiredField());
					}
				}
			});
			
			hp2.add(lc4Container);
			
			emailPhoneFieldSet.add(hp1);
			emailPhoneFieldSet.add(hp2);

			bookHisGrid = new GuestBookingHistoryGrid(CServiceConstants.CSERVICE_CONSTANTS.bookingHistory(),
					new SearchExecutor<BookingViewModelData, MainPaginationSearchModel>() {

						@Override
						public void doSearch(final MainPaginationSearchModel searchModel,
								final AsyncCallback<BasePagingLoadResult<BookingViewModelData>> callback) {
							final long propId = bViewModel.getEntity().getPropertyId();
							final long guestId = bViewModel.getEntity().getGuestProfileId();
							BookingServiceController.getInstance().getBookingHistory(propId, guestId, 0, 20,
									new AsyncCallbackListener<SearchResultsContainer<BookingView>>() {

										@Override
										public void onLogin(String username) {
											BookingServiceController.getInstance().getBookingHistory(propId,
													guestId, 0, 20, this);
										}

										@Override
										public void onSuccess(SearchResultsContainer<BookingView> result) {
											if (null != result) {
												bHistoryList = new ArrayList<BookingViewModelData>();
												for (BookingView bv : result.getResults()) {
													bHistoryList.add(new BookingViewModelData(bv));
												}
												callback.onSuccess(FcsPanel.createPagingLoadResult(
														bHistoryList, searchModel.getCurrentPage(),
														searchModel.getResultsPerPage(), result.getTotalCnt()));
											}
										}

										@Override
										public void onFailure(Throwable caught) {
											MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(
													CoreConstants.CORE_CONSTANTS.system(),
													ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
													CoreConstants.CORE_CONSTANTS.systemError(), null);
										}
									});

						}
					});
			bookHisGrid.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "5px");
			bookHisGrid.setId("FolioDialog_bookHisGrid_id");
			bookHisGrid.setFrame(false);
			
			inDiningGrid = new InRoomDiningHistoryGrid(CServiceConstants.CSERVICE_CONSTANTS.in_RoomDiningHistory(), new SearchExecutor<BookingViewModelData, MainPaginationSearchModel>() {

				@Override
				public void doSearch(MainPaginationSearchModel searchModel,
						AsyncCallback<BasePagingLoadResult<BookingViewModelData>> callback) {
					
					
					
				}
			});
			inDiningGrid.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "5px");
			inDiningGrid.setId("FolioDialog_inDiningGrid_id");
			inDiningGrid.setFrame(false);

			saveBtn = new FormButton(CoreConstants.CORE_CONSTANTS.save());
			saveBtn.setId("PublicAreaEConnectDialog_saveBtn_Id");
			saveBtn.addSelectionListener(new SelectionListener<ButtonEvent>() {

				@Override
				public void componentSelected(ButtonEvent ce) {

					isValid(new ValidationListener() {

						@Override
						public void onValidate(boolean good) {
							if (good) {
								if ((emailCheckBox.getValue() && null == emailCheckField.getValue())
										&& (phoneCheckBox.getValue() && null != phoneCheckField.getValue())) {
									emailCheckField.forceInvalid(CoreConstants.CORE_CONSTANTS.requiredField());
									return;
								}
								if ((phoneCheckBox.getValue() && null == phoneCheckField.getValue())
										&& (emailCheckBox.getValue() && null != emailCheckField.getValue())) {
									emailCheckField.forceInvalid(CoreConstants.CORE_CONSTANTS.requiredField());
									return;
								}
								if ((phoneCheckBox.getValue() && null == phoneCheckField.getValue())
										&& (emailCheckBox.getValue() && null == emailCheckField.getValue())) {
									emailCheckField.forceInvalid(CoreConstants.CORE_CONSTANTS.requiredField());
									emailCheckField.forceInvalid(CoreConstants.CORE_CONSTANTS.requiredField());
									return;
								}
								submit(SubmitType.DEFAULT);
							}
						}
					});
				}
			});
			getButtonBar().add(saveBtn);

			cancelBtn = new FormButton(CoreConstants.CORE_CONSTANTS.cancel());
			cancelBtn.setId("PublicAreaEConnectDialog_cancelBtn_Id");
			cancelBtn.addSelectionListener(new SelectionListener<ButtonEvent>() {
				@Override
				public void componentSelected(ButtonEvent ce) {
					ResBookingDetailDialog.this.hide();
					cancelBtn.removeStyleName(CoreConstants.CSS_FORM_BUTTON_FOCUS);
				}
			});
			getButtonBar().add(cancelBtn);

			add(lc1);
			add(lc2);
			add(emailPhoneFieldSet);
			add(bookHisGrid);
			add(inDiningGrid);
		}

		@Override
		public void setFocus() {

		}

		@Override
		public void show() {
			super.show();
			loadTitleList(bViewModel.getEntity().getPropertyId());
		}

		@Override
		public void updateForm(BookingUpdate entity) {
			
		}

		@Override
		public void populateEntity(BookingUpdate entity) {
			entity.setOrgId(bViewModel.getEntity().getOrgId());
			entity.setPropertyId(bViewModel.getEntity().getPropertyId());
			entity.setRestaurantId(bViewModel.getEntity().getRestaurantId());
			entity.setGuestId(bViewModel.getEntity().getGuestProfileId());
			entity.setBookingId(bViewModel.getEntity().getBookingId());
			entity.setGuestFirstName(currModel.getFirstName());
			entity.setGuestLastName(currModel.getLastName());
			if ((smokingCombox.getRawValue().toString()).equals(SmokingOrNotGWTEnum.SMOKING.toString())) {
				entity.setSmoking(true);
			}else {
				entity.setSmoking(false);
			}
			if (bookingStatusCombox.getRawValue().toUpperCase().equals(BookingStatusGWTEnum.PENDING.toString())) {
				entity.setBookingStatus(BookingStatus.PENDING);
			}
			if (bookingStatusCombox.getRawValue().toUpperCase().equals(BookingStatusGWTEnum.CANCEL.toString())) {
				entity.setBookingStatus(BookingStatus.CANCEL);
			}
			if (bookingStatusCombox.getRawValue().toUpperCase().equals(BookingStatusGWTEnum.COMPLETED.toString())) {
				entity.setBookingStatus(BookingStatus.COMPLETED);
			}
			if (bookingStatusCombox.getRawValue().toUpperCase().equals(BookingStatusGWTEnum.CONFIRMED_BOOKING.toString())) {
				entity.setBookingStatus(BookingStatus.CONFIRMED_BOOKING);
			}
			if (bookingStatusCombox.getRawValue().toUpperCase().equals(BookingStatusGWTEnum.FAILED.toString())) {
				entity.setBookingStatus(BookingStatus.FAILED);
			}
			if (bookingStatusCombox.getRawValue().toUpperCase().equals(BookingStatusGWTEnum.NO_SHOW.toString())) {
				entity.setBookingStatus(BookingStatus.NO_SHOW);
			}
			if (bookingStatusCombox.getRawValue().toUpperCase().equals(BookingStatusGWTEnum.WAITING_LIST.toString())) {
				entity.setBookingStatus(BookingStatus.WAITING_LIST);
			}
			
			entity.setArrivalDate(currModel.getArrivalDate());
			entity.setDepartureDate(currModel.getDepartureDate());
			entity.setNoOfGuest(Integer.valueOf(numOfPeopleField.getValue()));
			entity.setPhoneNumber(phoneField.getValue());
			entity.setReservationDate(formatDate.parse(datetimeReser.getRawValue()+" "+timeField.getRawValue()+":00"));
			entity.setGender(currModel.getGender());
			List<NotifyType> notifyLs = new ArrayList<NotifyType>();
			if (emailCheckBox.getValue()) {
				notifyLs.add(NotifyType.EMAIL);
				entity.setNotifyList(notifyLs);
				entity.setEamil(emailCheckField.getValue());
					
			}else {
				entity.setEamil("");
			}
			if (phoneCheckBox.getValue()) {
				notifyLs.add(NotifyType.PHONE);
				entity.setNotifyList(notifyLs);
				entity.setPhoneNumber(phoneCheckField.getValue());
			}else {
				entity.setPhoneNumber("");
			}

			entity.setSmoking(currModel.getSmoking());

			// entity.setBookingStatus();
			
		}
		
		
	}
	
	public void loadTitleList(final Long propId){
		CServiceCommonServiceController.getINSTANCE().getTitleList(propId, new AsyncCallbackListener<List<Title>>() {

			@Override
			public void onLogin(String username) {
				CServiceCommonServiceController.getINSTANCE().getTitleList(propId,this);
			}

			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(
						CoreConstants.CORE_CONSTANTS.system(),
						ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
						CoreConstants.CORE_CONSTANTS.systemError(), null);
			}

			@Override
			public void onSuccess(List<Title> result) {
				if (null != result) {
					titleStore.removeAll();
					for (Title title : result) {
						titleStore.add(new TitleModelData(title));
					}
				}
			}
		});
	}

	private void newSearch() {
		String term = null;
		MainPaginationSearchModel sm = new MainPaginationSearchModel();
		sm.setSearchTerm(term);
		bookHisGrid.newSearch(sm);
	}

	@Override
	public void hide() {
		super.hide();
	}
	
	public void clear() {
		titleCombobox.clear();
		numOfPeopleField.clear();
		phoneField.clear();
		roomNumAF.clear();
		guestTypeCombo.clear();
		datetimeReser.clear();
//		timeField.clear();
		emailCheckBox.clear();
		emailCheckField.clear();
		phoneCheckBox.clear();
		phoneCheckField.clear();
	}
	
	public void updateBookingView(BookingView entity) {
		currModel = entity;
		if (null != entity.getGuestProfileNo()) {
			guestProfileNumLabel.setText(entity.getGuestProfileNo());
		}
		if (null != entity.getArrivalDate()) {
			arriveDateLabel.setText(formatDate.format(entity.getArrivalDate()));
		}
		if (null != entity.getDepartureDate()) {
			departureDateLabel.setText(formatDate.format(entity.getDepartureDate()));
		}
		if (null != entity.getPhoneNo()) {
			phoneField.setValue(entity.getPhoneNo());
		}
		if (entity.getSmoking()) {
			smokingCombox.setValue(new SmokingOrNotGWTEnumModelData(SmokingOrNotGWTEnum.SMOKING));
		} else {
			smokingCombox.setValue(new SmokingOrNotGWTEnumModelData(SmokingOrNotGWTEnum.NON_SMOKING));
		}
		
		if (null != entity.getStatus()) {
			if (entity.getStatus().toString().equals(BookingStatus.CANCEL.toString())) {
				bookingStatusCombox.setValue(new BookingStatusModelData(BookingStatusGWTEnum.CANCEL));
			}
			if (entity.getStatus().toString().equals(BookingStatus.COMPLETED.toString())) {
				bookingStatusCombox.setValue(new BookingStatusModelData(BookingStatusGWTEnum.COMPLETED));
			}
			if (entity.getStatus().toString().equals(BookingStatus.CONFIRMED_BOOKING.toString())) {
				bookingStatusCombox.setValue(new BookingStatusModelData(
						BookingStatusGWTEnum.CONFIRMED_BOOKING));
			}
			if (entity.getStatus().toString().equals(BookingStatus.FAILED.toString())) {
				bookingStatusCombox.setValue(new BookingStatusModelData(BookingStatusGWTEnum.FAILED));
			}
			if (entity.getStatus().toString().equals(BookingStatus.NO_SHOW.toString())) {
				bookingStatusCombox.setValue(new BookingStatusModelData(BookingStatusGWTEnum.NO_SHOW));
			}
			if (entity.getStatus().toString().equals(BookingStatus.PENDING.toString())) {
				bookingStatusCombox.setValue(new BookingStatusModelData(BookingStatusGWTEnum.PENDING));
			}
			if (entity.getStatus().toString().equals(BookingStatus.WAITING_LIST.toString())) {
				bookingStatusCombox.setValue(new BookingStatusModelData(BookingStatusGWTEnum.WAITING_LIST));
			}
		}
		if (null != entity.getTitle()) {
			Title titleStr = new Title();
			titleStr.setTitle(entity.getTitle());
			titleCombobox.setValue(new TitleModelData(titleStr));
		}
		if (null != entity.getRoomNo()) {
//			roomNumAF.setValue(entity.getRoomNo());
			roomNumLab.setText(entity.getRoomNo());
		}
		if (null != entity.getGuestType()) {
			if (entity.getGuestType().equals(GuestProfileType.IN_HOUSE_GUEST.toString())) {
				guestTypeCombo.setValue(new GuestProfileTypeEnumModelData(GuestProfileTypeGWTEnum.IN_HOUSE_GUEST));
			}
			if (entity.getGuestType().equals(GuestProfileType.NON_IN_HOUSE_GUEST.toString())) {
				guestTypeCombo.setValue(new GuestProfileTypeEnumModelData(GuestProfileTypeGWTEnum.NON_IN_HOUSE_GUEST));
			}
		}
		if (null != entity.getReservationDate()) {
			datetimeReser.setValue(entity.getReservationDate());
			Time time = new Time(entity.getReservationDate(),timeFormat.format(entity.getReservationDate()));
			timeField.setValue(time);
		}
		if (null != entity.getNote()) {
			noteField.setValue(entity.getNote());
		}
		if (null != entity.getFirstName() || null != entity.getLastName()) {
			guestNameLabel.setText(entity.getLastName()+entity.getLastName());
		}
		numOfPeopleField.setValue(String.valueOf(entity.getNoOfGuest()));
		
		if (entity.getNotify().equals(NotifyType.EMAIL.toString())) {
			emailCheckBox.setValue(true);
			emailCheckField.setEnabled(true);
			emailCheckField.setValue(entity.getEmail());
		} 
		if (entity.getNotify().equals(NotifyType.PHONE.toString())) {
			phoneCheckBox.setValue(true);
			phoneCheckField.setEnabled(true);
			phoneCheckField.setValue(entity.getPhoneNo());
		}
		if (entity.getNotify().equals(NotifyType.EMAIL.toString()+"|"+NotifyType.PHONE.toString())) {
			emailCheckBox.setValue(true);
			emailCheckField.setEnabled(true);
			emailCheckField.setValue(entity.getEmail());
			phoneCheckBox.setValue(true);
			phoneCheckField.setEnabled(true);
			phoneCheckField.setValue(entity.getPhoneNo());
		}
		
		if (entity.getGuestType().equals(GuestProfileType.IN_HOUSE_GUEST.toString())) {
			arriveDateField.setVisible(true);
			departureDateField.setVisible(true);
		}else {
			arriveDateField.setVisible(false);
			departureDateField.setVisible(false);
		}
	}

	@Override
	public void formSubmitCallBack(FcsFormPanel<BookingUpdate> form, SubmitType submitType) {
		if (null != listener) {
			listener.formSubmitCallBack(form, submitType);
		}
	}

	@Override
	protected FcsFormPanel<BookingUpdate> getFormPanel() {
		return myFormPanel;
	}
}
